<template>
	<!-- 申请成为服务商 -->
	<view class="sqcwfws">
		<view class="content">
			<view class="main">
				<view class="row">
					<view class="left">企业名称</view>
					<view class="right">
						<input type="text" v-model="form.companyName" placeholder="请输入企业名称" :disabled="isView" />
					</view>
				</view>
				<view class="row">
					<view class="left">联系人</view>
					<view class="right">
						<input type="text" v-model="form.realName" placeholder="请输入联系人" :disabled="isView" />
					</view>
				</view>
				<view class="row">
					<view class="left">手机号</view>
					<view class="right">
						<input type="number" v-model="form.telphone" placeholder="请输入手机号" :disabled="isView" />
					</view>
				</view>
				<view class="row">
					<view class="left">微信号</view>
					<view class="right">
						<input type="text" v-model="form.weixin" placeholder="请输入微信号" :disabled="isView" />
					</view>
				</view>
				<view class="row row-column">
					<view class="left">企业简介</view>
					<view class="right">
						<textarea class="textarea" v-model="form.qyjj" placeholder="请输入企业简介" :disabled="isView" />
					</view>
				</view>
				<view class="row row-column">
					<view class="left">企业需求图片<text>（避免审核不通过，建议上传高清图片，大小比例4:3。）</text></view>
					<view class="right">
						<view class="upload-wrapper">
							<view class="upload-btn" @click="chooseImage('qyjjXp')" v-if="!isView && !form.qyjjXp">
								<uni-icons type="plusempty" size="30" color="#999"></uni-icons>
								<text>上传图片</text>
							</view>
							<view class="image-list" v-if="form.qyjjXp">
								<image :src="form.qyjjXp" mode="aspectFill" @click="previewImage(form.qyjjXp)"></image>
								<view class="delete-btn" @click="confirmDelete('qyjjXp')" v-if="!isView">
									<text class="delete-icon">×</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="row row-column">
					<view class="left">企业需求描述</view>
					<view class="right">
						<textarea class="textarea" v-model="form.qyxqms" placeholder="请输入企业需求描述(最多15个字)"
							:disabled="isView" maxlength="15" />
					</view>
				</view>
				<view class="row row-column">
					<view class="left">主营业务</view>
					<view class="right">
						<textarea class="textarea" v-model="form.zyyw" placeholder="请输入主营业务" :disabled="isView" />
					</view>
				</view>
				<view class="row row-column">
					<view class="left">产品图片<text>（避免审核不通过，建议上传高清图片）</text></view>
					<view class="right">
						<view class="upload-wrapper">
							<view class="image-list1">
								<view class="image-item" v-for="(item, index) in form.zzzmList" :key="index">
									<image :src="item" mode="aspectFill" @click="previewImage(item)"></image>
									<view class="delete-btn" @click="confirmDelete('zzzmList', index)" v-if="!isView">
										<text class="delete-icon">×</text>
									</view>
								</view>
								<view class="upload-btn" @click="chooseImage('zzzmList')"
									v-if="!isView && (!form.zzzmList || form.zzzmList.length < 9)">
									<uni-icons type="plusempty" size="30" color="#999"></uni-icons>
									<text>上传图片</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="left">服务商分类</view>
					<view class="right">
						<picker :range="fwsflOptions" :value="fwsflIndex" @change="onFwsflChange" mode="selector"
							:disabled="isView">
							<view class="picker">
								<input type="text" disabled
									:value="fwsflIndex === -1 ? '请选择服务商分类' : fwsflOptions[fwsflIndex]"
									placeholder="请选择服务商分类" />
								<uni-icons type="right" size="17" color="#adadad"></uni-icons>
							</view>
						</picker>
					</view>
				</view>
				<view class="row row-column" v-if="showServiceScope">
					<view class="left">服务范围</view>
					<view class="right">
						<view class="checkbox-group">
							<checkbox-group @change="onServiceScopeChange" :disabled="isView">
								<label class="checkbox-item" v-for="(item, index) in serviceScopeOptions" :key="index">
									<checkbox :value="item" :checked="form.serviceScope.includes(item)"
										:disabled="isView" />
									<text>{{item}}</text>
								</label>
							</checkbox-group>
						</view>
					</view>
				</view>
				<view class="row">
					<view class="left">会员</view>
					<view class="right">
						<switch :checked="form.hyzt" @change="onHyztChange" color="#EF8441" :disabled="isView" />
					</view>
				</view>
				<view class="tip-text">
					<text>1、请确保填写的信息真实有效；</text>
					<text>2、请勿发布违反国家法律法规的内容。</text>
				</view>
			</view>
			<button class="submit-btn" @click="submit" :class="{ active: isBtnActive }" @touchstart="isBtnActive = true"
				@touchend="isBtnActive = false" v-if="!isView">
				{{ isEdit ? '确认修改' : '提交' }}
			</button>
			<button class="submit-btn" @click="goBack" :class="{ active: isBtnActive }" @touchstart="isBtnActive = true"
				@touchend="isBtnActive = false" v-else>
				返回
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isView: false,
				isEdit: false,
				form: {
					companyName: '',
					realName: '',
					telphone: '',
					weixin: '',
					qyjj: '',
					qyjjXp: '',
					qyxqms: '',
					zyyw: '',
					zzzmList: [],
					fwsfl: '',
					serviceScope: [],
					hyzt: false
				},
				isBtnActive: false,
				fwsflOptions: ['产品资源', '行业服务', '培训机构'],
				fwsflIndex: -1,
				showServiceScope: false,
				serviceScopeOptions: [],
				productResources: [
					'个人信贷',
					'消费金融',
					'企业融资',
					'信用卡',
					'房产抵押',
					'车辆抵押',
					'产品续贷',
					'债务重组',
					'债务优化',
					'民间配资',
					'垫资过桥',
					'融资租赁',
					'贸易增量',
					'供应链金融',
					'不良资产处置'
				],
				industryServices: [
					'企业咨询',
					'财务税筹',
					'企业注册',
					'CRM系统',
					'信息流投放',
					'项目加盟',
					'外呼专线',
					'短信群发',
					'催收服务',
					'法务咨询',
					'征信异议',
					'支付通道',
					'共享办公',
					'电销卡'
				]
			}
		},
		onLoad(options) {
			if (options.id) {
				if (options.type === 'view') {
					this.isView = true;
				} else if (options.type === 'edit') {
					this.isEdit = true;
				}
				this.getDetail(options.id);
			}
		},
		methods: {
			async getDetail(id) {
				try {
					// 调用获取详情接口
					const res = await this.$api.getSwsListDetails({
						guid: id
					});
					if (res.succ) {
						// 确保zzzmList被正确初始化
						this.form = {
							...res.data
						};
						this.fwsflIndex = this.fwsflOptions.indexOf(this.form.fwsfl);

						// 处理serviceScope数据
						if (this.form.serviceScope && this.form.serviceScope.length > 0) {
							// 直接使用服务范围数组，不需要转换
							this.form.serviceScope = this.form.serviceScope;
						}

						if (this.form.fwsfl === '产品资源') {
							this.showServiceScope = true;
							this.serviceScopeOptions = this.productResources;
						} else if (this.form.fwsfl === '行业服务') {
							this.showServiceScope = true;
							this.serviceScopeOptions = this.industryServices;
						}
					}
				} catch (error) {
					console.error('获取详情失败:', error);
					uni.showToast({
						title: '获取详情失败',
						icon: 'none'
					});
				}
			},
			goBack() {
				uni.navigateBack();
			},
			onFwsflChange(e) {
				this.fwsflIndex = e.detail.value;
				this.form.fwsfl = this.fwsflOptions[this.fwsflIndex];
				this.form.serviceScope = [];

				if (this.form.fwsfl === '产品资源') {
					this.showServiceScope = true;
					this.serviceScopeOptions = this.productResources;
				} else if (this.form.fwsfl === '行业服务') {
					this.showServiceScope = true;
					this.serviceScopeOptions = this.industryServices;
				} else {
					this.showServiceScope = false;
				}
			},
			onServiceScopeChange(e) {
				// 直接使用选中的值
				this.form.serviceScope = e.detail.value;
			},
			onHyztChange(e) {
				this.form.hyzt = e.detail.value;
			},
			// 选择图片
			async chooseImage(type) {
				uni.chooseImage({
					count: type === 'zzzmList' ? (9 - (this.form.zzzmList || []).length) : 1,
					sizeType: ['compressed', 'original'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						if (!res.tempFilePaths || res.tempFilePaths.length === 0) {
							return;
						}

						if (type === 'zzzmList') {
							for (const filePath of res.tempFilePaths) {
								await this.uploadSingleFile(filePath, type);
							}
						} else {
							// 企业需求图片4:3裁剪
							uni.cropImage({
								src: res.tempFilePaths[0],
								cropScale: '4:3',
								quality: 100,
								success: async (cropRes) => {
									await this.uploadSingleFile(cropRes.tempFilePath, type);
								},
								fail: () => {
									uni.showToast({
										title: '裁剪失败',
										icon: 'none'
									});
								}
							});
						}
					},
					fail: () => {
						// 用户取消选择时不显示提示
					}
				});
			},
			// 上传单个文件
			async uploadSingleFile(filePath, type) {
				return new Promise((resolve, reject) => {
					uni.showLoading({
						title: '上传中...',
						mask: true
					});
					
					uni.uploadFile({
						url: 'https://luntan.xiaouyf.cn/apis/custom/service/upload',
						filePath: filePath,
						name: 'multipartFile',
						formData: {
							'type': type
						},
						success: (uploadRes) => {
							const result = JSON.parse(uploadRes.data);
							if (result.code === 200) {
								const imageUrl = 'https://luntan.xiaouyf.cn' + result.data;
								if (type === 'zzzmList') {
									this.form.zzzmList.push(imageUrl);
								} else {
									this.form[type] = imageUrl;
								}
								resolve();
							} else {
								reject(new Error(result.msg || '上传失败'));
							}
						},
						fail: (error) => {
							reject(new Error('上传失败: ' + JSON.stringify(error)));
						},
						complete: () => {
							uni.hideLoading();
						}
					});
				}).catch(error => {
					uni.showToast({
						title: error.message || '上传失败',
						icon: 'none'
					});
				});
			},
			// 预览图片
			previewImage(url) {
				let urls = [];
				if (url.includes('zzzm')) {
					urls = this.form.zzzmList;
				} else {
					urls = [url];
				}
				uni.previewImage({
					urls: urls,
					current: url
				});
			},
			// 删除图片
			deleteImage(type) {
				this.form[type] = '';
			},
			// 确认删除
			confirmDelete(type, index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					success: (res) => {
						if (res.confirm) {
							if (type === 'zzzmList') {
								this.form.zzzmList.splice(index, 1);
							} else {
								this.deleteImage(type);
							}
						}
					}
				});
			},
			// 提交
			async submit() {
				// 表单验证
				if (!this.form.companyName) {
					uni.showToast({
						title: '请输入企业名称',
						icon: 'none'
					});
					return;
				}
				if (!this.form.realName) {
					uni.showToast({
						title: '请输入联系人',
						icon: 'none'
					});
					return;
				}
				// 姓名校验：2-20个字符，只能包含中文、英文、数字和下划线
				if (!/^[\u4e00-\u9fa5a-zA-Z0-9_]{2,20}$/.test(this.form.realName)) {
					uni.showToast({
						title: '联系人姓名格式不正确',
						icon: 'none'
					});
					return;
				}
				if (!this.form.telphone) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return;
				}
				// 手机号校验：11位数字，以1开头
				if (!/^1[3-9]\d{9}$/.test(this.form.telphone)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					});
					return;
				}
				if (!this.form.weixin) {
					uni.showToast({
						title: '请输入微信号',
						icon: 'none'
					});
					return;
				}
				if (!this.form.qyjj) {
					uni.showToast({
						title: '请输入企业简介',
						icon: 'none'
					});
					return;
				}
				if (!this.form.qyjjXp) {
					uni.showToast({
						title: '请上传企业需求图片',
						icon: 'none'
					});
					return;
				}
				if (!this.form.qyxqms) {
					uni.showToast({
						title: '请输入企业需求描述',
						icon: 'none'
					});
					return;
				}
				if (!this.form.zyyw) {
					uni.showToast({
						title: '请输入主营业务',
						icon: 'none'
					});
					return;
				}
				if (!this.form.fwsfl) {
					uni.showToast({
						title: '请选择服务商分类',
						icon: 'none'
					});
					return;
				}
				if (this.showServiceScope && this.form.serviceScope.length === 0) {
					uni.showToast({
						title: '请选择服务范围',
						icon: 'none'
					});
					return;
				}
				if (this.form.zzzmList.length === 0) {
					uni.showToast({
						title: '请上传产品图片',
						icon: 'none'
					});
					return;
				}

				try {
					console.log(this.form)
					this.form.createUserId = this.$store.state.user.userInfo.guid;
					// 转换会员状态为中文
					this.form.hyzt = this.form.hyzt ? '是' : '否';

					let res;
					if (this.isEdit) {
						// 编辑状态下调用更新接口，添加guid参数
						const updateData = {
							...this.form,
							guid: this.form.guid // 添加guid参数
						};
						res = await this.$api.getServiceUpdateInfo(updateData);
					} else {
						// 新增状态下调用原来的接口
						res = await this.$api.infoServiceApply(this.form);
					}

					if (res.succ) {
						uni.showToast({
							title: this.isEdit ? '修改成功' : '提交成功',
							icon: 'success'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}

				} catch (error) {
					uni.showToast({
						title: this.isEdit ? '修改失败' : '提交失败',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style lang="less">
	.sqcwfws {
		height: 100%;
		background: linear-gradient(180deg, #FAEBDB 0%, rgba(255, 247, 238, 0) 500rpx);

		.content {
			flex: 1;
			display: flex;
			flex-direction: column;
			overflow: hidden;
			padding: 0 30rpx;

			.main {
				flex: 1;
				display: flex;
				flex-direction: column;
				overflow: auto;
			}
		}

		.row {
			position: relative;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: #333;

			&:after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 1px;
				background-color: #e8e8e8;
				transform: scaleY(0.5);
			}

			.left {
				font-size: 32rpx;
				padding: 40rpx 0;
			}

			.right {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: flex-end;

				input {
					width: 100%;
					border: 0;
					text-align: right;
					font-size: 32rpx;
					color: #333;
				}

				.picker {
					width: 100%;
					display: flex;
					align-items: center;

					input {
						flex: 1;
						margin-right: 10rpx;
						color: #333;
					}
				}
			}

			&.row-column {
				flex-direction: column;
				align-items: flex-start;

				&::after {
					display: none;
				}

				.left {
					text {
						color: #999;
						font-size: 26rpx;
					}
				}

				.right {
					width: 100%;
					flex: none;

					.textarea {
						width: 100%;
						height: 200rpx;
						padding: 20rpx 30rpx;
						box-sizing: border-box;
						border: 1px solid #e8e8e8;
						border-radius: 10rpx;
						color: #333;
					}

					.upload-wrapper {
						width: 100%;

						.upload-btn {
							width: 200rpx;
							height: 200rpx;
							background: #F5F5F5;
							border-radius: 10rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;

							text {
								font-size: 24rpx;
								color: #999;
								margin-top: 10rpx;
							}
						}

						.image-list {
							position: relative;
							width: 200rpx;
							height: 200rpx;

							image {
								width: 100%;
								height: 100%;
								border-radius: 10rpx;
							}
						}

						.delete-btn {
							position: absolute;
							top: -20rpx;
							right: -20rpx;
							width: 44rpx;
							height: 44rpx;
							background: #fff;
							border-radius: 50%;
							display: flex;
							align-items: center;
							justify-content: center;
							border: 2rpx solid #ff4d4f;
							box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);

							.delete-icon {
								color: #ff4d4f;
								font-size: 36rpx;
								font-weight: bold;
								line-height: 1;
								margin-top: -4rpx;
							}
						}

						.image-list1 {
							display: flex;
							flex-wrap: wrap;

							.image-item {
								position: relative;
								width: 200rpx;
								height: 200rpx;
								margin: 0 20rpx 20rpx 0;

								image {
									width: 200rpx;
									height: 200rpx;
									border-radius: 10rpx;
								}

								.delete-btn {
									position: absolute;
									top: -20rpx;
									right: -20rpx;
									width: 44rpx;
									height: 44rpx;
									background: #fff;
									border-radius: 50%;
									display: flex;
									align-items: center;
									justify-content: center;
									border: 2rpx solid #ff4d4f;
									box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);

									.delete-icon {
										color: #ff4d4f;
										font-size: 36rpx;
										font-weight: bold;
										line-height: 1;
										margin-top: -4rpx;
									}
								}
							}

							.upload-btn {
								width: 200rpx;
								height: 200rpx;
								background: #F5F5F5;
								border-radius: 10rpx;
								display: flex;
								flex-direction: column;
								align-items: center;
								justify-content: center;
								margin: 0 20rpx 20rpx 0;

								text {
									font-size: 24rpx;
									color: #999;
									margin-top: 10rpx;
								}
							}
						}
					}

					.checkbox-group {
						width: 100%;
						display: flex;
						flex-wrap: wrap;
						padding: 20rpx 0;

						.checkbox-item {
							display: inline-flex;
							align-items: center;
							margin: 0 20rpx 20rpx 0;
							padding: 10rpx 0;
							box-sizing: border-box;

							checkbox {
								transform: scale(0.8);
								margin-right: 5rpx;
							}

							checkbox .wx-checkbox-input {
								border-color: #EF8441;
								background: transparent;
							}

							checkbox .wx-checkbox-input.wx-checkbox-input-checked {
								background: transparent;
								border-color: #EF8441;
							}

							checkbox .wx-checkbox-input.wx-checkbox-input-checked::before {
								color: #EF8441;
							}

							text {
								font-size: 28rpx;
								color: #333;
								line-height: 1.4;
								flex: 1;
							}
						}
					}
				}
			}
		}

		.tip-text {
			display: flex;
			flex-direction: column;
			align-items: flex-start;
			margin: 30rpx 0;
			padding: 30rpx;
			background: #FFF7EE;
			border-radius: 10rpx;

			text {
				margin-bottom: 20rpx;
				font-size: 28rpx;
				color: #AC6C17;

				&:last-child {
					margin-bottom: 0;
				}
			}
		}

		.submit-btn {
			margin: 40rpx 0;
			height: 88rpx;
			line-height: 88rpx;
			background: linear-gradient(138deg, #F3B359 0%, #EC6A34 100%);
			border-radius: 44rpx;
			color: #fff;
			font-size: 32rpx;

			&.active {
				opacity: 0.8;
			}
		}

		/* 修改picker确认按钮颜色 */
		::v-deep .uni-picker-action-confirm {
			color: #EF8441 !important;
		}
	}
</style>